package com.nokia.examplegame;

import java.util.*;

import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.GameCanvas;

public class SplashScreenView extends GameCanvas {

	private Image[] images;
	private int currentImage = -1;
	private int timeout;
	private Displayable next;
	private Display display;
	private Timer timer;

	public SplashScreenView(Display display, Displayable next,
			Image[] images, int timeout) {
		super(false);
		this.images = images;
		this.timeout = timeout;
		this.next = next;
		this.display = display;
		this.setFullScreenMode(true);
		if ((images != null) && (images.length > 0)) {
			this.currentImage = 0;
		} else {
			this.currentImage = -1;
		}
	}

	public void paint(Graphics graphics) {
		if (currentImage != -1) {
			graphics.drawImage(images[currentImage], 0, 0, Graphics.LEFT | Graphics.TOP);
		} else {
			graphics.setColor(0,0,0);
			graphics.fillRect(0,0,this.getWidth(), this.getHeight());
		}
	}

	protected void pointerPressed(int x, int y) {
		showNextImage();
	}

	protected void keyPressed(int keyCode) {
		showNextImage();
	}

	protected void showNotify() {
		if ((images != null) && (images.length > 0)) {
			this.currentImage = 0;
		} else {
			this.currentImage = -1;
		}
		scheduleTimer();
	}

	private void scheduleTimer() {
		try {
			this.timer = new Timer();
			this.timer.schedule(new CountDown(), timeout);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	private void closeSplashScreen() {
		this.timer.cancel();
		this.currentImage = -1;
		repaint();
		this.display.setCurrent(next);
	}

	private void showNextImage() {
		if (currentImage + 1 >= images.length) {
			closeSplashScreen();
		} else {
			if (this.currentImage != -1) {
				currentImage++;
				repaint();
				scheduleTimer();
			}
		}
	}

	private class CountDown extends TimerTask {
		public void run() {
			showNextImage();
		}
	}
}